<template>
  <page-header-wrapper :title="false">
    <a-row>
      <a-col :span="12">
        <a-card>
          <div style="margin-bottom: 16px">
            <a-button type="primary" style="margin-left: 8px" @click="handleAdd(false)">添加部门</a-button>
            <a-button type="primary" style="margin-left: 8px" @click="handleAdd(true)">添加下级</a-button>
            <a-button type="primary" style="margin-left: 8px" @click="exportExcel" icon="export">导出部门</a-button>
            <a-button style="margin-left: 8px" @click="delHa_departs">批量删除</a-button>
          </div>
          <div class="spin-content">
            当前选择：{{ selectedKeys.length > 0 ? departName : '' }}
            <a v-if="selectedKeys.length > 0" style="margin-left: 10px" @click="() => (selectedKeys = [])">取消选择</a>
          </div>
          <div>
            <a-input-search style="margin-bottom: 8px" placeholder="请输入部门名称" @change="onChange" />
            <a-tree
              :expanded-keys="expandedKeys"
              :auto-expand-parent="autoExpandParent"
              :replaceFields="{ children: 'children', title: 'name', key: 'id' }"
              checkable
              showIcon
              showLine
              :tree-data="data"
              @expand="onExpand"
              @select="onSelect"
              @check="onCheck"
              :checkStrictly="checkStrictly"
              v-model="checkedKeys"
            >
              <template slot="title" slot-scope="{ name }">
                <span v-if="searchValue && name.substr(name.indexOf('_') + 1).indexOf(searchValue) > -1">
                  <!-- userid为12_user，只取_后面的user作为显示和查询结果-->
                  {{
                    name.substring(
                      name.indexOf('_') + 1,
                      name.substr(name.indexOf('_') + 1).indexOf(searchValue) + 1 + name.indexOf('_')
                    )
                  }}
                  <span style="color: #f50">{{ searchValue }}</span>
                  <!-- userid为12_user，只取_后面的user作为显示和查询结果-->
                  {{
                    name.substr(
                      name.indexOf('_') +
                        1 +
                        name.substr(name.indexOf('_') + 1).indexOf(searchValue) +
                        searchValue.length
                    )
                  }}
                </span>
                <span v-else>{{ name.substr(name.indexOf('_') + 1) }}</span>
              </template>
            </a-tree>
          </div>
          <a-divider />
          <a-popover trigger="click" :visible="clicked" @visibleChange="(visible) => (clicked = visible)">
            <template style="margin: 0; padding: 0" slot="content">
              <div class="li" @click="addStrictly" @mousemove="addColor($event)" @mouseout="reColor($event)">
                <span>父子关联</span>
              </div>
              <div class="li" @click="reStrictly" @mousemove="addColor($event)" @mouseout="reColor($event)">
                <span>取消关联</span>
              </div>
              <div class="li" @click="checkAll" @mousemove="addColor($event)" @mouseout="reColor($event)">
                <span>全部勾选</span>
              </div>
              <div class="li" @click="reCheckAll" @mousemove="addColor($event)" @mouseout="reColor($event)">
                <span>取消全选</span>
              </div>
              <div class="li" @click="expandAll" @mousemove="addColor($event)" @mouseout="reColor($event)">
                <span>展开所有</span>
              </div>
              <div class="li" @click="reExpandAll" @mousemove="addColor($event)" @mouseout="reColor($event)">
                <span>合并所有</span>
              </div>
            </template>
            <a-button> 树操作 <a-icon type="up" /> </a-button>
          </a-popover>
        </a-card>
      </a-col>
      <a-col :span="12" style="padding-left: 5px">
        <a-card>
          <a-tabs default-active-key="org" :activeKey="activeTab">
            <a-tab-pane key="org">
              <span slot="tab">
                <a-icon type="home" />
                基本信息
              </span>
              <a-row>
                <a-col :span="24">
                  <edit v-if="selectedKeys.length > 0" ref="view" @reloadList="findTreeData"></edit>
                  <a-empty v-else description="请先选一个部门！" />
                </a-col>
              </a-row>
            </a-tab-pane>
          </a-tabs>
          <a-modal title="添加部门" :visible="visible" @cancel="visible = false" :footer="null">
            <edit ref="add" @close="visible = false" @reloadList="findTreeData"></edit>
          </a-modal>
        </a-card>
      </a-col>
    </a-row>
  </page-header-wrapper>
</template>

<style scoped>
.ant-popover-inner-content {
  padding: 0px 0px !important;
}
.li {
  cursor: pointer;
  padding: 5px 12px;
}
</style>

<script>
import { delHa_departs, output, quyeryTreeData } from '@/api/base/ha_depart'
import edit from '@/views/base/Ha_departEdit'

const getParentKey = (id, tree) => {
  let parentKey
  for (let i = 0; i < tree.length; i++) {
    const node = tree[i]
    if (node.children) {
      if (node.children.some((item) => item.id === id)) {
        parentKey = node.id
      } else if (getParentKey(id, node.children)) {
        parentKey = getParentKey(id, node.children)
      }
    }
  }
  return parentKey
}
const dataList = [] // 所有书节点的id
const generateList = (data) => {
  for (let i = 0; i < data.length; i++) {
    const node = data[i]
    const id = node.id
    const name = node.name
    let arr = dataList.filter((item) => {
      return item.id == id
    })
    if (arr.length > 0) {
      continue
    }
    dataList.push({ id, name })
    if (node.children) {
      generateList(node.children)
    }
  }
}
export default {
  data() {
    return {
      queryParam: {}, // 查询条件
      data: [], //数据
      expandedKeys: [], //展开指定的树节点
      searchValue: '', // 搜索值
      autoExpandParent: true, //是否自动展开父节点
      checkedKeys: [], // 勾选的部门ids
      checkStrictly: true, // 完全受控
      selectedKeys: [], // 选中的ids
      departName: '', // 选中的节点
      clicked: false, // 书操作提示语悬浮
      visible: false, // 添加部门弹框
      activeTab: 'org', // 展示的tab
    }
  },
  created() {
    this.findTreeData()
  },
  methods: {
    addColor($event) {
      $event.currentTarget.style.backgroundColor = '#E6F7FF'
    },
    reColor($event) {
      $event.currentTarget.style.backgroundColor = ''
    },
    addStrictly() {
      this.checkStrictly = false
      this.clicked = false
    },
    reStrictly() {
      this.checkStrictly = true
      this.clicked = false
    },
    reCheckAll() {
      this.checkedKeys = []
      this.clicked = false
    },
    checkAll() {
      this.checkedKeys = dataList.map((item) => {
        return item.id
      })
      this.clicked = false
    },
    reExpandAll() {
      this.expandedKeys = []
      this.clicked = false
    },
    expandAll() {
      this.expandedKeys = dataList.map((item) => {
        return item.id
      })
      this.clicked = false
    },
    onExpand(expandedKeys) {
      this.expandedKeys = expandedKeys
      this.autoExpandParent = false
    },
    onSelect(selectedKeys, info) {
      this.selectedKeys = selectedKeys
      this.departName = info.node.dataRef.name.substr(6)
      selectedKeys.length > 0 && this.handleEdit(selectedKeys[0].substr(7))
    },
    onCheck(checkedKeys) {
      if (checkedKeys.length) {
        this.checkedKeys = checkedKeys
      } else {
        this.checkedKeys = checkedKeys.checked
      }
    },
    onChange(e) {
      const value = e.target.value
      console.log('dataList', dataList)
      const expandedKeys = dataList
        .map((item) => {
          if (item.name.indexOf(value) > -1) {
            console.log('this.treeData', this.data)
            return getParentKey(item.id, this.data)
          }
          return null
        })
        .filter((item, i, self) => item && self.indexOf(item) === i)
      Object.assign(this, {
        expandedKeys,
        searchValue: value,
        autoExpandParent: true,
      })
    },
    // 查询树下拉的数据
    findTreeData() {
      quyeryTreeData().then((res) => {
        if (res.code === 0 && res.data) {
          generateList(res.data)
          console.log(dataList)
          this.data = res.data
        }
      })
    },
    /**
     * 进入新增页面
     */
    handleAdd(isChild) {
      if (isChild && this.selectedKeys.length == 0) {
        this.$message.warn('请先点击选中上级部门！')
        return
      }
      this.visible = true
      setTimeout(() => {
        this.$refs.add.resetForm()
        if (isChild) {
          this.$refs.add.isAdd = false
          this.$refs.add.ha_depart.parent = this.selectedKeys[0].substr(7)
          this.$refs.add.parentName = this.departName
        } else {
          this.$refs.add.isAdd = true
          this.$refs.add.ha_depart.parent = 0
        }
      }, 0)
    },
    /**
     * 进入编辑页面
     */
    handleEdit(id) {
      setTimeout(() => {
        this.$refs.view.findHa_departById(id)
        this.$refs.view.parentName = this.departName
      }, 0)
    },
    getChild(nodes, id, arr) {
      for (let el of nodes) {
        if (el.id === id) {
          arr.push(el.id)
          if (el.children) {
            this.childNodesDeep(el.children, arr)
          }
        } else if (el.children) {
          this.getChild(el.children, id, arr)
        }
      }
      return arr
    },
    childNodesDeep(nodes, arr) {
      if (nodes)
        nodes.forEach((ele) => {
          arr.push(ele.id)
          if (ele.children) {
            this.childNodesDeep(ele.children, arr)
          }
        })
    },

    /**
     * 批量删除部门
     */
    delHa_departs() {
      if (this.checkedKeys.length == 0) {
        this.$message.warn('请选择一条记录！')
        return
      }
      this.$confirm({
        title: '确认删除?',
        content: `确定要删除所选中的 ${this.checkedKeys.length} 条数据，以及子节点数据吗?`,
        onOk: () => {
          // 存放选中的父节点和子节点，原始departids
          let departArr = []
          // 循环父节点，递归查找子节点
          for (let index = 0; index < this.checkedKeys.length; index++) {
            // 如果父节点在存放原始departids的数组中则跳过，不需要递归，否则递归查找子节点，查找到的原始id放入departArr
            if (departArr.includes(this.checkedKeys[index])) {
              continue
            }
            departArr.concat(this.getChild(this.data, this.checkedKeys[index], departArr))
          }
          // 把原始id转为正常的id
          let ids = departArr.map((item) => {
            return item.substr(7)
          })
          // 去重，一般情况不会有重复，以防万一
          ids = Array.from(new Set(ids))
          delHa_departs({ ids: ids.toString() }).then((res) => {
            if (res.code !== 0) {
              this.$message.success(res.msg)
            } else {
              // 删除后清除之前勾选的部门
              this.checkedKeys = []
              // 如果删除的部门中有正在编辑页面的，不显示编辑页面
              if (this.selectedKeys.length > 0 && departArr.includes(this.selectedKeys[0])) {
                this.selectedKeys = []
              }
              this.findTreeData()
              this.$message.success('删除成功')
            }
          })
        },
        onCancel: () => {},
      })
    },
    /**
     *  导出Excel
     */
    exportExcel() {
      output(this.queryParam)
        .then((response) => {
          var blob = new Blob([response])
          var downloadElement = document.createElement('a')
          var href = window.URL.createObjectURL(blob) //创建下载的链接
          downloadElement.href = href
          downloadElement.download = '部门.xls' //下载后文件名
          document.body.appendChild(downloadElement)
          downloadElement.click() //点击下载
          document.body.removeChild(downloadElement) //下载完成移除元素
          window.URL.revokeObjectURL(href) //释放掉blob对象
        })
        .catch(function () {
          console.log(error)
        })
    },
  },
  components: {
    edit,
  },
}
</script>